﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace LPBToolsLib
{
    public class HttpReqTools
    {

        private static readonly string DefaultUserAgent_FireFox = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/112.0";
        private static readonly string DefaultUserAgent_Chrome = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36";
        private static readonly string DefaultUserAgent_QQ = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.196.400 QQBrowser/11.7.5286.400";
        /// <summary>
        /// Http的Post请求
        /// </summary>
        /// <param name="Url">目标地址</param>
        /// <param name="Paras">参数列表</param>
        /// <param name="appDHeader">追加的请求头，每行内必须包含冒号 (:) 字符</param>
        /// <returns></returns>
        public static string PostJSON(string Url, Dictionary<string, object> Paras,
            Dictionary<string, object> appDHeader, int timeOut = 5000)
        {
            if (Paras != null)
            {
                List<string> tHeaders = new List<string>();
                if ((appDHeader != null) && (appDHeader.Count > 0))
                    foreach (KeyValuePair<string, object> item in appDHeader)
                        tHeaders.Add(item.Key + ":" + item.Value);
                return PostJSON(Url, JsonConvert.SerializeObject(Paras),
                    tHeaders.ToArray(), timeOut);
            }
            return "";
        }

        /// <summary>
        /// Http的Post请求
        /// </summary>
        /// <param name="Url">目标地址</param>
        /// <param name="jsonParas">参数列表，必须是JSON格式的字符串</param>
        /// <param name="appHeaders">追加的请求头，每行内必须包含冒号 (:) 字符</param>
        /// <returns></returns>
        public static string PostJSON(string Url, string jsonParas, string[] appHeaders,
             int timeOut = 5000)
        {
            string strURL = Url;
            string postContent = "";
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json;charset:utf-8";
            request.KeepAlive = true;
            request.UserAgent = DefaultUserAgent_FireFox;
            request.Timeout = timeOut;
            // 可能的异常:
            //   T:System.ArgumentException:
            //     header 不包含冒号 (:) 字符。 value 的长度大于 65535。 或 - header 的名称部分为 System.String.Empty，或者包含无效字符。
            //     或 - header 是应由属性设置的受限制的标头。 或 header 的值部分包含无效字符。
            if ((appHeaders != null) && (appHeaders.Length > 0))
                foreach (string item in appHeaders)
                    request.Headers.Add(item);

            //设置参数
            //进行URL编码 System.Web.HttpUtility.UrlEncode(jsonParas);
            string paraUrlCoded = jsonParas;

            byte[] payload;
            //将Json字符串转化为字节  
            payload = Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求，获得请求流 

            Stream writer = null;
            try
            {
                //获取用于写入请求数据的Stream对象
                writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();//关闭请求流
                    writer = null;
                }
            }
            // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            Stream sTmp = null;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
                sTmp = response.GetResponseStream();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                throw;
            }
            if (sTmp != null)
            {
                StreamReader sRead = null;
                try
                {
                    sRead = new StreamReader(sTmp);
                    postContent = sRead.ReadToEnd();
                }
                finally
                {
                    if (sRead != null)
                    {
                        sRead.Close();
                        sRead = null;
                    }
                }
            }
            return postContent;//返回Json数据
        }
    }
}
